const DataLoader = require('dataloader')
import { sequelize, Document, Progress } from '../../models'
import { placeData } from '../../lib/graphql'

export const documentLoader = () =>
  new DataLoader(
    async keys => {
      let data = await Document.findAll({ where: { id: { $in: keys } } })
      return placeData(keys, data, 'id')
    },
    { cacheKeyFn: key => key.toString() }
  )

export const unreadCountLoaderByDocument = () =>
  new DataLoader(
    async keys => {
      const data = await Progress.findAll({
        group: ['documentId'],
        attributes: [
          'documentId',
          [sequelize.fn('COUNT', 'documentId'), 'unreadCount']
        ],
        where: { documentId: { $in: keys }, unreadCount: 1 }
      })
      // pull finishCount from dataValues
      for (let i in data) {
        data[i].unreadCount = data[i].dataValues.unreadCount
      }

      return placeData(keys, data, 'documentId', 0, 'unreadCount')
    },
    { cacheKeyFn: key => key.toString() }
  )
